package com.beeantec.jnrerc.modules.comment.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beeantec.jnrerc.core.api.dto.PagingReqDTO;
import com.beeantec.jnrerc.dto.CommentVo;
import com.beeantec.jnrerc.dto.MemberVo;
import com.beeantec.jnrerc.dto.request.CommentListReqDTO;
import com.beeantec.jnrerc.entity.Comment;
import com.beeantec.jnrerc.entity.Exam;
import com.beeantec.jnrerc.entity.Member;
import com.beeantec.jnrerc.mapper.CommentMapper;
import com.beeantec.jnrerc.modules.comment.service.CommentService;
import com.beeantec.jnrerc.modules.member.service.MemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    private static final Integer APPROVAL_STATUS_CHECK = 0;
    private static final Integer APPROVAL_STATUS_PASS = 1;
    private static final Integer APPROVAL_STATUS_NO_PASS = 2;
    private static final Integer AUTO_REVIEW_REVIEW_RESULT = 0;
    private static final Integer AUTO_REVIEW_PASS_RESULT = 1;
    private static final Integer AUTO_REVIEW_BLOCK_RESULT = 2;
    private static final Integer COMMENT_LIKE_YES = 1;
    private static final Integer COMMENT_LIKE_NO = 0;
    private static final Integer FIRST_LEVEL = 1;
    private static final Integer SECOND_LEVEL = 2;

    @Autowired
    private CommentService commentService;


    @Autowired
    private MemberService memberService;




    private Integer newsCommentCounts = 0;


    @Override
    public List<Long> listIdsExcludeFail(Comment comment) {
        return baseMapper.selectlistIdsExcludeFail(comment);
    }
    @Override
    public Integer countExcludeFail(Comment comment) {
        return baseMapper.countExcludeFail(comment);
    }











    /**
     * 添加评论
     *
     * @param comment
     * @return
     */
    @Override
    public Boolean add(Comment comment) {
        Integer autoReviewResult =  AUTO_REVIEW_PASS_RESULT ;
        comment.setAutoReviewResult(autoReviewResult);
        comment.setState( APPROVAL_STATUS_PASS );
        comment.setReviewTime( new Date());
        comment.setPraiseCount(0);
        comment.setAnswerCount(0);
        Long parentId = comment.getParentId();
        comment.setLevel(FIRST_LEVEL);
        comment.setCreateTime(new Date(System.currentTimeMillis()));
        comment.setUpdateTime(new Date());
        boolean insert = comment.insert();
        if (parentId != null) {
            addParentAnswerCount(parentId);
            comment.setFirstLevelId(new Comment().selectOne(new QueryWrapper<Comment>().eq(Comment.COMMENT_ID, parentId)).getFirstLevelId());
            if (!parentId.equals(comment.getFirstLevelId())) {
                //一级评论增加回复数量
                addParentAnswerCount(comment.getFirstLevelId());
            }
        } else {
            comment.setFirstLevelId(comment.getCommentId());
        }
        comment.updateById();

        if (insert) {
            CommentVo commentVo = CommentVo.create();
            BeanUtil.copyProperties(comment, commentVo);
            if (parentId != null) {
                CommentVo parentComent = new CommentVo();
                MemberVo info = new MemberVo();
                BeanUtils.copyProperties(commentService.getById(parentId),parentComent);
                BeanUtils.copyProperties(memberService.getById(parentComent.getMemberId()),info);
                commentVo.setBeAnswerMemberName(info.getNickName());
            }
            commentVo.setOwner(0);

            if (!ObjectUtils.isEmpty(commentVo)) {
                Integer exsitMemberId = commentVo.getMemberId();
                MemberVo memberVo = new MemberVo();
                BeanUtils.copyProperties(memberService.getById(exsitMemberId),memberVo);
                commentVo.setNickName(memberVo.getNickName());
                commentVo.setAvatarUrl(memberVo.getAvatarUrl());
            }
            return true;
        }
        return false;
    }

    @Transactional
    public void addParentAnswerCount(Long parentId) {
        Comment comment = new Comment().selectOne(new QueryWrapper<Comment>().eq(Comment.COMMENT_ID, parentId));
        Integer before = comment.getAnswerCount();
        comment.setAnswerCount(++before);
        comment.updateById();
    }


    /**
     * 获取评论数通过的
     *
     * @param answerId
     * @param answerType
     * @return
     */
    public Map<String, Integer> count(String answerId, Integer answerType) {
        Map<String, Integer> result = new HashMap<>();
        QueryWrapper<Comment> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(Comment::getState,APPROVAL_STATUS_PASS)
                .eq(Comment::getAnswerId,answerId)
                .eq(Comment::getAnswerType,answerType);
        result.put("amount", commentService.count(queryWrapper));
        return result;
    }

    /**
     * 获取评论数排除未通过，通过和未审核
     *
     * @param answerId
     * @param answerType
     * @return
     */
    public Map<String, Integer> countExcludeFail(String answerId, Integer answerType) {
        Map<String, Integer> result = new HashMap<>();
        Comment comment = new Comment();
        comment.setState(APPROVAL_STATUS_NO_PASS);
        comment.setAnswerId(answerId);
        comment.setAnswerType(answerType);
        result.put("amount", commentService.countExcludeFail(comment));
        return result;
    }





    /**
     * 获取内容
     */
    public CommentVo getHotCommentsByNewsId(Integer newsId) {
        //获取评论列表
        //展示规则：
        //评论赞数  ≥ 10条，展示赞数最多的一条评论。如赞数一样，则展示时间最早的一条
        //评论赞数 ＜ 10条，隐藏热评
        List<Comment> commentList = new Comment().selectList(new QueryWrapper<Comment>().eq(Comment.ANSWER_ID, newsId)
                .eq(Comment.ANSWER_TYPE, 0)
                .eq(Comment.LEVEL, 1)
                .eq(Comment.STATE, 1)
                .eq(Comment.DELETED, 1)
                .orderByDesc(Comment.PRAISE_COUNT).orderByAsc(Comment.CREATE_TIME));
        CommentVo commentVo = new CommentVo();
        if (CollectionUtils.isEmpty(commentList)) {
            return commentVo;
        }
        String commentCounts = String.valueOf(commentList.size());
        Comment comment = commentList.get(0);
        if (comment.getPraiseCount() >= newsCommentCounts) {
            BeanUtils.copyProperties(comment, commentVo);
            MemberVo info = new MemberVo();
            BeanUtils.copyProperties(memberService.getById(comment.getMemberId()),info);
            if (info != null) {
                commentVo.setNickName(info.getNickName());
                commentVo.setAvatarUrl(info.getAvatarUrl());
            }
        }
        commentVo.setCommentCounts(commentCounts);
        return commentVo;
    }

    @Override
    public IPage<Comment> page(Integer page,Integer size,Integer contentId,Integer type) {
        //分页查询并转换
        QueryWrapper<Comment> examQueryWrapper = new QueryWrapper<>();
        examQueryWrapper.lambda().eq(Comment::getAnswerId,contentId)
                .eq(Comment::getAnswerType,type)
        .orderByDesc(Comment::getCreateTime);
        Page<Comment> cPage = new Page<>(page, size);
        IPage<Comment> examIPage = getBaseMapper().selectPage(cPage,examQueryWrapper);

        return examIPage;
    }

//    private CommentVo getWrapCommentVo(CommentVo commentVo) {
//        String createTime = commentVo.getCreateTime();
//        LocalDateTime ctime = LocalDateTime.parse(createTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        LocalDateTime now = LocalDateTime.now();
//
//        if (ctime.plusMinutes(1L).compareTo(now) > 0) {
//            commentVo.setCreateTime("1分钟前");
//            return commentVo;
//        }
//        if (ctime.plusHours(1L).compareTo(now) > 0) {
//            Duration between = Duration.between(ctime, now);
//            commentVo.setCreateTime(between.toMinutes() + "分钟前");
//            return commentVo;
//        }
//        if (ctime.plusHours(24L).compareTo(now) > 0) {
//            Duration between = Duration.between(ctime, now);
//            commentVo.setCreateTime(between.toHours() + "小时前");
//            return commentVo;
//        }
//        if (ctime.plusHours(48L).compareTo(now) > 0) {
//            commentVo.setCreateTime("昨天");
//            return commentVo;
//        }
//        if (ctime.plusDays(4L).compareTo(now) > 0) {
//            Duration between = Duration.between(ctime, now);
//            commentVo.setCreateTime(between.toDays() + "天前");
//            return commentVo;
//        }
//        commentVo.setCreateTime(ctime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//        return commentVo;
//    }
}
